package com.sunny.dao.mongo.download;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.DBObject;
import com.sunny.dao.mongo.MongoDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Sunny on 2016/4/25.
 */
@Service
public class ImageDownload {

    public static int imageTotalNumber = 0;
    @Autowired
    MongoDao mongoDao;


    public static int  perThread = 10;

    Logger logger = LoggerFactory.getLogger(ImageDownload.class);



    public void download(int threadNum ){
        int j = 0;
        if (threadNum == 1){
            j = 1;
        }
       // for(j;j<=perThread;j++){
        while(j < perThread){
            System.out.println("线程数"+threadNum);
            int perSkip = (threadNum-1)*perThread + j;
            int skip = perSkip * 20000;
            logger.info(perSkip+"=="+skip);
            List<DBObject> lists = new ArrayList<DBObject>();
            try {
                lists = mongoDao.findByFields( 0, 20000);
                System.out.println(lists.size()+"+=============");
            } catch (Exception e) {
                logger.error("query data exception,threadNum={},batchNum={},message={}",threadNum,perThread, e.getMessage());
                e.printStackTrace();
                continue;
            }
            for (DBObject object : lists) {
                try {
                    dealDBObject(object, perSkip);
                } catch (IOException e) {
                    logger.error("解析查询所得json异常,threadNum={},batchNum={},message={}",threadNum,perThread, e.getMessage());
                    e.printStackTrace();
                }
            }
            j++;
        }
    }

    public void downLoadImage(){
        int counts = Integer.parseInt(mongoDao.getMongoTemplate().count(null,MongoDao.collectionName)+"");
        int per = 20000;
        int count = counts / per ==0?counts/per:counts/per +1;
        List<DBObject> lists = new ArrayList<DBObject>();
       for(int i =1 ;i<2;i++){
            try{
                //lists = mongoDao.findByFieldsQuery(new Query(),per*i,per);
                logger.info(lists.size()+"==========="+i);
            }catch (Exception e){
                logger.error("查询数据异常,文件数量={},message={}",i,e.getMessage());
                e.printStackTrace();
            }
            for(DBObject object:lists){
                try {
                    dealDBObject(object,i);
                } catch (IOException e) {
                    logger.error("解析查询所得json异常,文件数量={}",i);
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 将查询所得数据处理之后存放到map中。
     * @param objectList
     * @return  List<Map<String,String>>
     */
    private List<Map<String,String>> dealDBObject(List<DBObject> objectList ){
        List<Map<String,String>> mapList = new ArrayList<Map<String, String>>();
        for(DBObject object:objectList){
            Map<String,String> map = new HashMap<String, String>();
            ObjectMapper mapper = new ObjectMapper();
            JsonNode node = null;
            try {
                node = mapper.readTree(object.toString());
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }
            String credit_id 		=  node.get("credit_id") == null     ?"":node.get("credit_id").toString().replaceAll("\"","");
            String credit_front		=node.get("credit_front") == null    ?"":node.get("credit_front").toString().replaceAll("\"","");
            String personal_pic		=node.get("personal_pic") == null    ?"":node.get("personal_pic").toString().replaceAll("\"","");
            String credit_back		=node.get("credit_back") == null     ?"":node.get("credit_back").toString().replaceAll("\"","");
            String student_id_pic	=node.get("student_id_pic") == null  ?"":node.get("student_id_pic").toString().replaceAll("\"","");
            String fee_list_pic		=node.get("fee_list_pic") == null    ?"":node.get("fee_list_pic").toString().replaceAll("\"","");
            String user_info_pic	=node.get("user_info_pic") == null   ?"":node.get("user_info_pic").toString().replaceAll("\"","");
            String dorm_pic			=node.get("dorm_pic") == null        ? "":node.get("dorm_pic").toString().replaceAll("\"","");
            String school_roll_pic	=node.get("school_roll_pic") == null   ?"":node.get("school_roll_pic").toString().replaceAll("\"","");
            String contract_front	=node.get("contract_front") == null   ?"":node.get("contract_front").toString().replaceAll("\"","");
            String chis_school_rol_pic = node.get("chis_school_rol_pic") == null?"":node.get("chis_school_rol_pic").toString().replaceAll("\"","");
            String intranet_school_rol_pic = node.get("intranet_school_rol_pic") == null?"":node.get("intranet_school_rol_pic").toString().replaceAll("\"","");

            map.put("credit_id",credit_id);
            map.put("credit_front",credit_front);
            map.put("personal_pic",personal_pic);
            map.put("credit_back",credit_back	);
            map.put("student_id_pic",student_id_pic);
            map.put("fee_list_pic",fee_list_pic	);
            map.put("user_info_pic",user_info_pic);
            map.put("dorm_pic",dorm_pic		);
            map.put("school_roll_pic",school_roll_pic);
            map.put("contract_front",contract_front);
            map.put("chis_school_rol_pic",chis_school_rol_pic);
            map.put("intranet_school_rol_pic",intranet_school_rol_pic);
            mapList.add(map);
        }
        //总处理
        return mapList;
    }

    private void dealDBObject(DBObject object,int dirIndex) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode node =  mapper.readTree(object.toString());
        String title = "http://cimg.fenqile.com";
        String order_id = node.get("order_id").toString().replaceAll("\"","");
        String credit_id 		=  node.get("credit_id") == null     ?"":node.get("credit_id").toString().replaceAll("\"","");
        String credit_front		=node.get("credit_front") == null    ?"":node.get("credit_front").toString().replaceAll("\"","");
        String personal_pic		=node.get("personal_pic") == null    ?"":node.get("personal_pic").toString().replaceAll("\"","");
        String credit_back		=node.get("credit_back") == null     ?"":node.get("credit_back").toString().replaceAll("\"","");
        String student_id_pic	=node.get("student_id_pic") == null  ?"":node.get("student_id_pic").toString().replaceAll("\"","");
        String fee_list_pic		=node.get("fee_list_pic") == null    ?"":node.get("fee_list_pic").toString().replaceAll("\"","");
        String user_info_pic	=node.get("user_info_pic") == null   ?"":node.get("user_info_pic").toString().replaceAll("\"","");
        String dorm_pic			=node.get("dorm_pic") == null        ? "":node.get("dorm_pic").toString().replaceAll("\"","");
        String school_roll_pic	=node.get("school_roll_pic") == null   ?"":node.get("school_roll_pic").toString().replaceAll("\"","");
        String contract_front	=node.get("contract_front") == null   ?"":node.get("contract_front").toString().replaceAll("\"","");
        String chis_school_rol_pic = node.get("chis_school_rol_pic") == null?"":node.get("chis_school_rol_pic").toString().replaceAll("\"","");
        String intranet_school_rol_pic = node.get("intranet_school_rol_pic") == null?"":node.get("intranet_school_rol_pic").toString().replaceAll("\"","");
        String fileName = order_id+"_"+credit_id+"_"+credit_front.replaceAll("/","_");
        if(!credit_front.equals("")) {
            saveUrlAs(credit_id,title+credit_front, dirIndex,credit_id+"credit_front+"+credit_front.replaceAll("/","_"));
        }
        if(!credit_back.equals("")) {
            saveUrlAs(credit_id,title+credit_back, dirIndex,credit_id+"_credit_back_"+credit_back.replaceAll("/","_"));
        }
        if(!personal_pic.equals("")) {
            saveUrlAs(credit_id,title+personal_pic, dirIndex,credit_id+"_personal_pic_"+personal_pic.replaceAll("/","_"));
        }
        if(!student_id_pic.equals("")) {
            saveUrlAs(credit_id,title+student_id_pic, dirIndex,credit_id+"_student_id_pic_"+student_id_pic.replaceAll("/","_"));
        }
        if(!fee_list_pic.equals("")) {
            saveUrlAs(credit_id,title+fee_list_pic, dirIndex,credit_id+"_fee_list_pic_"+fee_list_pic.replaceAll("/","_"));
        }
        if(!user_info_pic.equals("")) {
            saveUrlAs(credit_id,title+user_info_pic, dirIndex,credit_id+"_user_info_pic_"+user_info_pic.replaceAll("/","_"));
        }
        if(!dorm_pic.equals("")) {
            saveUrlAs(credit_id,title+dorm_pic, dirIndex,credit_id+"_dorm_pic_"+dorm_pic.replaceAll("/","_"));
        }
        if(!school_roll_pic.equals("")) {
            saveUrlAs(credit_id,title+school_roll_pic, dirIndex,credit_id+"_school_roll_pic_"+school_roll_pic.replaceAll("/","_"));
        }
        if(!contract_front.equals("")) {
            saveUrlAs(credit_id,title+contract_front, dirIndex,credit_id+"_contract_front_"+contract_front.replaceAll("/","_"));
        }
        if(!chis_school_rol_pic.equals("")) {
            saveUrlAs(credit_id,title+chis_school_rol_pic, dirIndex,credit_id+"_chis_school_rol_pic_"+chis_school_rol_pic.replaceAll("/","_"));
        }
        if(!intranet_school_rol_pic.equals("")) {
            saveUrlAs(credit_id,title+intranet_school_rol_pic, dirIndex,credit_id+"_intranet_school_rol_pic_"+intranet_school_rol_pic.replaceAll("/","_"));
        }

    }
     public  boolean saveUrlAs(String credit_id,String fileUrl,int dirIndex,String savePath){
        URL url =null;
        InputStream is = null;
        OutputStream os = null;
         try {
             url = new URL(fileUrl);
         } catch (MalformedURLException e) {
            logger.error("url exeption={}",fileUrl);
             return false;
             //e.printStackTrace();
         }
         String fileStr = "D:\\threadimages\\" + dirIndex;
         File file = new File(fileStr);
         if(!file.exists()){
             logger.info("create direction exception ={}",fileStr);
             file.mkdir();
         }
         try {
             is =  url.openStream();
         } catch (IOException e) {
             logger.error("download exception,credit_id={},message={}",credit_id,e.getMessage());
             return false;
         }
         try {
             os = new FileOutputStream(fileStr+"\\"+savePath);
         } catch (FileNotFoundException e) {
             logger.error("upload exception,credit_id={},message={}}",credit_id,e.getMessage());
             //e.printStackTrace();
             return false;
         }
         byte[] buffer = new byte[4096];
         int count = 0;
         try {
             while ((count = is.read(buffer)) > 0){
                 os.write(buffer, 0, count);
             }
         } catch (IOException e) {
          //   e.printStackTrace();
             logger.error("write exception ,credit_id={},message={}}",credit_id,e.getMessage());
             return false;
         }finally {
            try {
              if(null != os)  os.close();
                if(null != is)  is.close();
            } catch (IOException e) {
                logger.error("close resources exception,credit_id={},message={}}",credit_id,e.getMessage());
            }
        }
        return false;
    }


    public MongoDao getMongoDao() {
        return mongoDao;
    }

    public void setMongoDao(MongoDao mongoDao) {
        this.mongoDao = mongoDao;
    }
}
